﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace AliyunDDNS.Core
{
    public class Md5Helper
    {
        /// <summary>
        /// 获取字符串MD5Hash值（该方法返回的MD5长度可为16或32位，也可设置输入字符大小写，要获得带'-'分割符的易读模式请使用重载方法）
        /// </summary>
        /// <param name="input">要获取MD5的原始字符串</param>
        /// <param name="outLength">输出的MD5字符串长度，默认为32位，传入其它值输出16位</param>
        /// <param name="outLower">输出的MD5字符串字母大小写，默认为小写模式</param>
        /// <returns>MD5Hash</returns>
        public static string GetMd5(string input, int outLength = 32, bool outLower = true)
        {
            if (string.IsNullOrWhiteSpace(input)) throw new ArgumentNullException(nameof(input));

            using (var md5 = MD5.Create())
            {
                var data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                return outLength == 32 ? OutFormat(data, outLower) : OutFormat(data, outLower).Substring(8, 16);
            }
        }

        /// <summary>
        /// 获取字符串MD5Hash值(该方法返回的MD5字符串为32位大写模式，要输出小写模式或16位长度请使用重载方法)
        /// </summary>
        /// <param name="input">要获取MD5的原始字符串</param>
        /// <param name="readability">易读模式：值为true时输出带'-'分割符，值为false时输出不带'-'分割符</param>
        /// <returns>MD5Hash</returns>
        public static string GetMd5(string input, bool readability)
        {
            if (string.IsNullOrWhiteSpace(input)) throw new ArgumentNullException(nameof(input));

            using (var md5 = MD5.Create())
            {
                var data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                return readability ? BitConverter.ToString(data) : BitConverter.ToString(data).Replace("-", "");
            }
        }

        private static string OutFormat(byte[] data, bool outLower = true)
        {
            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString(outLower ? "x2" : "X2"));
            }

            return sBuilder.ToString();
        }
    }
}
